<template>
	<view class="">
		<uni-nav-bar fixed="true" :border="false">
			<view class="search-box u-flex align-center">
				<view class="search-input-box u-flex align-center">
					<view class="img-box">
						<image class="image100" src="../../static/indexImages/searchicon.png" mode=""></image>
					</view>
					<view class="flex_alitm">
						<input v-model="keyword" type="text" style="font-size: 14px;" placeholder="搜你想要的商品">
					</view>
					<view class="screen-box d-flex align-center justify-space-between ml-4">
						<view class="search-btn" @click="handAddagent">
							<text>+代理商</text>
						</view>
						<view class="export screen-item d-flex align-center"  @click="handScreen(1)">
							<image class="shai" src="../../static/orderImages/screen.png" mode=""></image>
						</view>
						<view class="export screen-item d-flex align-center" @click="handScreen(2)">
							<image class="shai" src="../../static/orderImages/arrow.png" mode=""></image>
						</view>
					</view> 
				</view>
			</view> 
		</uni-nav-bar>
		<view class="content">
			<view class="card-box mt-2" v-for="(item , index) in  agent" :key="index+'agent'">
				<view class="userinfo d-flex align-center">
					<view class="code-box mr-2"><text>账号</text></view>
					<view class="font-bold font-20"><text>{{item.name}}</text></view>
					<!-- <view class="tag ml-2 tag1  d-flex align-center">
						<image class="icon" src="../../static/agentImages/user-icon.png" mode=""></image>
						<text>{{item.realname==1 ? '未实名' : '已实名'}}</text>
					</view>
					<view class="tag ml-2 tag2 d-flex align-center">
						<image class="icon" src="../../static/agentImages/user-ri-icon.png" mode=""></image>
						<text>{{item.exam==1 ? '未审核' : '已审核'}}</text>
					</view> -->
				</view>
				<view class="d-flex align-center mt-2">
					<view class="mr-2 grey">联系方式：</view>
					<text class="recipient">{{item.statist_phone}}</text>
				</view>
				<view class="d-flex align-center mt-2">
					<view class="mr-2 grey">上级代理：</view>
					<text class="recipient">{{item.statist_name}}</text>
				</view>
				<!-- <view class="d-flex align-center mt-2">
					<view class="mr-2 grey">线上平台信息：</view>
					<text class="recipient">{{item.phone}}</text>
				</view> -->
				<view class="d-flex align-center mt-2">
					<view class="mr-2 grey">创建时间：</view>
					<text class="recipient">{{item.created_at}}</text>
				</view>
				<view class="data-box mt-2 d-flex">
					<view class="tab_itemorder flex-column justify-center align-center">
						<view class="font-22 font-bold mb-2"><text>{{item.totle || 0}}</text></view>
						<view><text>总订单</text></view>
					</view>
					<view class="tab_itemorder flex-column justify-center align-center">
						<view class="font-22 font-bold mb-2"><text>{{item.totleAct || 0}}</text></view>
						<view><text>总激活</text></view>
					</view>
					<view class="tab_itemorder flex-column justify-center align-center">
						<view class="font-22 font-bold mb-2"><text>{{item.totleMonth || 0}}</text></view>
						<view><text>月订单</text></view>
					</view>
					<view class="tab_itemorder flex-column justify-center align-center">
						<view class="font-22 font-bold mb-2"><text>{{item.totleMonthAct || 0}}</text></view>
						<view><text>月激活</text></view>
					</view>
				</view>
				<view class="d-flex align-center justify-space-between mt-2">
					<view @click="dumpPage('/pages/setConnission/setConnission',{shop_id:item.shop_id},'to')" class="tab-item d-flex align-center">
						<text>单个佣金设置</text>
						<uni-icons type="right" color="#F79E06" size="20"></uni-icons>
					</view>
					<view @click="handTabBatch(item.shop_id)" class="tab-item d-flex align-center">
						<text>批量佣金设置</text>
						<uni-icons type="right" color="#F79E06" size="20"></uni-icons>
					</view>
					<view @click="handTab(item.shop_id)" class="tab-item d-flex align-center">
						<text>重置密码</text>
						<uni-icons type="right" color="#F79E06" size="20"></uni-icons>
					</view>
				</view>
			</view>
			<page-empty  con="暂无代理~" v-if="isEmpty(agent)"></page-empty>
			<view class="">
				<uni-popup ref="popupPoster" closeable border-radius="10px">
					<view class="">
						<view class="Posterpopup" id="Posterbox" style="" ref="Posterbox">
							<!-- <view class=" d-flex justify-center">
								<image class="Posterpopup-image" src="../../static/23.png"  mode=""></image>
							</view> -->
							<l-painter ref="painter" css="width: 680rpx; height: 1000rpx">
								<l-painter-image src="../../static/23.png"
									css="width: 680rpx; height: 1000rpx" />
								<l-painter-qrcode :text="qrcodeUrl"
									css="width: 140rpx; height: 140rpx;position: absolute;bottom:70rpx;left:280rpx;" />
							</l-painter>
							<!-- <view class="ml-4 mt-6">
								<text style="color: #fff" class="mb-2">测试</text>
								<view class="">
									<text style="color: #fff;">提示</text>
								</view>
							</view> -->
							<!-- <view class="Posterpopup-code" style="margin-top: -90px;">
								<tki-qrcode :val="qrcodeUrl" :size="150" :onval="true" :load-make="true" />
								 <canvas id="qrcodecode" canvas-id="qrcodecode" style="width: 200px;height: 200px;"></canvas> 
							</view> -->
						</view>
						<view class=" mt-4 d-flex">
							<button size="mini" type="default" @click="PosterCancel">取消</button>
							<button size="mini" type="primary" @click="Posterdown">生成图片</button>
						</view>
					</view>
			
				</uni-popup>
				<uni-popup ref="popupPiliangfy" mode="center" :close-on-click-overlay="true" closeable border-radius="10px">
					<view class="Piliangfypopup" style="">
						<view class="title">
							<text class="">分佣(直接代理)</text>
						</view>
						<view class="Piliangfypopup-input">
							<input type="text" v-model="commission_money" placeholder="请输入批量分佣百分比" />
						</view>
						<view style="width: 80%;margin-left: 10%;">
							<text>说明:一次性批量分配给所有产品,例如:输入10%即可赚取下游10%的利润</text>
						</view>
						<view class="d-flex justify-space-around">
							<button size="mini" type="default" @click="submitFY">取消</button>
							<button size="mini" type="primary" @click="submitFYA">确认</button>
						</view>
					</view>
				</uni-popup>
				<uni-popup ref="popupMiMa" mode="center" :close-on-click-overlay="true" closeable border-radius="10px">
					<view class="Piliangfypopup" style="">
						<view class="title">
							<text class="">重置密码</text>
						</view>
						<view class="Piliangfypopup-input">
							<input type="text" disabled="true" val="112233" placeholder="112233" />
						</view>
						<view style="width: 80%;margin-left: 10%;color:red;">
							<text>友情提示:默认密码不可修改,保存成功后请及时通知代理</text>
						</view>
						<view class="d-flex justify-space-around">
							<button size="mini" type="default" @click="submitFYS">取消</button>
							<button size="mini" type="primary" @click="submitFYAS">确认</button>
						</view>
					</view>
				</uni-popup>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getToken
	} from '@/common/auth';
	import UQRCode from 'uqrcodejs';
	import html2canvas from 'html2canvas';
	import tkiQrcode from 'tki-qrcode'
	import {
				pathToBase64,
				base64ToPath
			} from 'image-tools'
	export default{
		components: {
			tkiQrcode
		},
		data(){
			return{
				keyword:'',
				city: '北京',
				agent:[],
				qrcodeUrl:'',
				commission_shop_id:'',
				shareBg: "https://img2.baidu.com/it/u=3334525604,928778682&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1703955600&t=c88ebba9f3d8aeee92c6afd219945f9a",
				
				agents:[
					{
						username:'Baihii',
						realname:1,//是否实名 1 未 2-已
						exam:1,//是否审核 1 未 2-已
						tel:'1879024524',
						superior:'小刘',//上级
						web:'淘宝',//平台
						addtime:'2024-08-01 15:15',
						allorder:55,
						activation:19,
						monthorder:5,
						monthactive:4
					},
					{
						username:'Baihii',
						realname:1,//是否实名 1 未 2-已
						exam:1,//是否审核 1 未 2-已
						tel:'1879024524',
						superior:'小刘',//上级
						web:'淘宝',//平台
						addtime:'2024-08-01 15:15',
						allorder:55,
						activation:19,
						monthorder:5,
						monthactive:4
					},
					{
						username:'Baihii',
						realname:1,//是否实名 1 未 2-已
						exam:1,//是否审核 1 未 2-已
						tel:'1879024524',
						superior:'小刘',//上级
						web:'淘宝',//平台
						addtime:'2024-08-01 15:15',
						allorder:55,
						activation:19,
						monthorder:5,
						monthactive:4
					},
					{
						username:'Baihii',
						realname:2,//是否实名 1 未 2-已
						exam:2,//是否审核 1 未 2-已
						tel:'1879024524',
						superior:'小张',//上级
						web:'拼多多',//平台
						addtime:'2024-08-01 15:15',
						allorder:55,
						activation:19,
						monthorder:5,
						monthactive:4
					},
				]
			}
		},
		onLoad() {
			let aShopId = uni.getStorageSync('shop_id');
			if ((aShopId)) {
				uni.$my.shopId = aShopId;
			}
			this.init();
			this.serverHost = uni.$my.serverHost;
			this.qrcodeUrl = uni.$my.currHost+'pages/register/register?invitId=' + uni.$my.shopId;
			// console.log(this.qrcodeUrl,444444444);
			// console.log(uni.$my.shopId,44444444);
		},
		methods:{
			isEmpty(item) {
				return uni.$uv.test.empty(item)
			},
			// dumpPage(page, params, type) {
			// 	// console.log(33333333333333);
			// 	uni.$my.dumpPage(page, params, type)
			// },
			// 添加代理商
			handAddagent(){
				let that = this;
				uni.showActionSheet({
					itemList: ['生成海报', '复制链接','手动添加'],
					success: function(res) {
						// console.log(res,44444444);
						// let te = uni.$my.goodsHost + id;
						if(res.tapIndex == 0){
							that.Generateposter();
							return true;
						}
						if(res.tapIndex == 1){
							that.handAddagentCopy();
							return true;
						}
						if(res.tapIndex == 2){
							// that.handAddagentCopy();
							that.dumpPage("/pages/registercomm/registercomm");
							return true;
						}
						// console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			Generateposter() {
				uni.showLoading({
					title: '生成中···'
				})
				// this.rowOne = item;
				
				this.$refs.popupPoster.open('center')
				uni.hideLoading()
			},
			PosterCancel() {
				this.$refs.popupPoster.close()
				
			},
			handAddagentCopy(){
				let test = uni.$my.currHost+'pages/register/register?invitId='+uni.$my.shopId;
				console.log(test,11111111);
				
				setTimeout(()=>{
				//#ifndef H5
					uni.setClipboardData({
						data: test, //需要字符串
						success: function () {
						  uni.showToast({
							title: '已复制链接',
							icon: 'success',
							duration: 2000
						  });
						},
						fail: (err) => {
							uni.showToast({
								title: err,
								icon: 'success',
								duration: 2000
							});
						}
					  });	
				//#endif
				//#ifdef H5
					let textarea = document.createElement("textarea")
						textarea.value = test
						textarea.readOnly = "readOnly"
						document.body.appendChild(textarea)
						textarea.select() // 选择对象
						textarea.setSelectionRange(0, test.length) //核心
						let result = document.execCommand("copy") // 执行浏览器复制命令
						if (result) {
							uni.showToast({
								title: '已复制链接',
								duration: 2000
							});
						}
						textarea.remove()
				//#endif
				})
			},
			// 筛选
			handScreen(index){
				uni.showToast({
					title:'开发中'
				})
			},
			handTab(item){
				// uni.showToast({
				// 	title:item
				// })
				this.commission_shop_id = item;
				this.$refs.popupMiMa.open('center');
			},
			// 所有的商品设置  按百分比设置
			handTabBatch(item){
				this.commission_shop_id = item;
				this.$refs.popupPiliangfy.open('center');
			},
			submitFYA() {
				let that = this;
				uni.$uv.http.post('/goods/goodsEditMoneyAll',{commission_money:this.commission_money,shop_ids:this.commission_shop_id}).then(res => {
					console.log(res);
					// let goodsName = this.products.in_name;
					uni.showToast({
						title:res.msg
					});
					setTimeout(()=>{
						that.$router.go(0);
					},300);
					this.$refs.popupPiliangfy.close();
				})
			},
			submitFY(){
				this.$refs.popupPiliangfy.close();
			},
			submitFYS(){
				this.$refs.popupMiMa.close();
			},
			submitFYAS(){
				// console.log(11111111);
				let that = this;
				uni.$uv.http.post('/updatePwdXc',{shop_id:this.commission_shop_id}).then(res => {
					console.log(res);
					// let goodsName = this.products.in_name;
					uni.showToast({
						title:res.msg
					});
					setTimeout(()=>{
						this.$refs.popupPiliangfy.close();
						that.$router.go(0);
					},300);
					
				})
			},
			init(){
				uni.$uv.http.post('/orders/orderStatist').then(res => {
					console.log(res,999999999);
					this.agent = res.data;
					// this.gridList = this.makeServerPicUrl(res.data.grid || '', 'pic')
					// this.swiperList = this.makeServerPicUrl(res.data.swiper || '', 'pic')
					// this.adList = this.makeServerPicUrl(res.data.ad || '', 'pic')
					// this.tabList = res.data.tab || []
					// this.popAd = this.makeServerPicUrl(res.data.pop || '', 'pic')
					// if (!this.isEmpty(this.popAd) && !this.isReInit) {
					// 	this.openPopAd()
					// }
					// if (!this.isEmpty(this.tabList)) {
					// 	this.getTabData()
					// }
					// console.log(res)
				}).catch(e => {
					console.log(e)
				})
			},
			dumpPage(page, params, type) {
				// console.log(33333333333333);
				uni.$my.dumpPage(page, params, type)
			},
			upimage(img){
				const nowToken = getToken();
				uni.uploadFile({
					url: '/dev-api/uploadPic', //仅为示例，非真实的接口地址
					filePath: img,
					name: 'file',
					header: {
						"Authorization": 'Bearer  ' + nowToken
					},
					formData: {
						img: 'file',
					},
					success: (uploadFileRes) => {
						let imgarr = []
						let res = JSON.parse(uploadFileRes.data);
						let url = this.serverHost + res.fileName;
						imgarr[0] = url
						uni.previewImage({ //图片预览
							current: 0,
							urls: imgarr
						});
					},
					fail: (err) => {
						alert(JSON.stringify(err))
					}
				});
			},
			Posterdown() {
				uni.showLoading({
					title: '生成中...'
				});
				this.$refs.painter.canvasToTempFilePathSync({
					fileType: "jpg",
					// 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
					pathType: 'url',
					quality: 1,
					success: (res) => {
						this.PosterCancel()
						// console.log(res.tempFilePath);
						// uni.previewImage({ //图片预览
						// 	current: 0,
						// 	urls: [res.tempFilePath]
						// });
						setTimeout(()=>{
							this.upimage(res.tempFilePath)	
							uni.hideLoading()
						},800);
						
						console.log(res.tempFilePath);
						// uni.uploadFile({
						// 	url: '/dev-api/uploadPic', //仅为示例，非真实的接口地址
						// 	filePath: res.tempFilePath,
						// 	name: 'file',
						// 	header: {
						// 		"Authorization": 'Bearer  ' + nowToken
						// 	},
						// 	formData: {
						// 		img: 'file',
						// 	},
						// 	success: (uploadFileRes) => {
						// 		let imgarr = []
						// 		let res = JSON.parse(uploadFileRes.data);
						// 		let url = this.serverHost + res.fileName;
						// 		imgarr[0] = url
						// 		uni.previewImage({ //图片预览
						// 			current: 0,
						// 			urls: imgarr
						// 		});
						// 	},
						// 	fail: (err) => {
						// 		alert(JSON.stringify(err))
						// 	}
						// });
					},
					fail: (err) => {
						console.log(err);
					}
				});
			},
			Posterdownx() {
				const nowToken = getToken();
				const content = this.$refs.Posterbox;
				const dom = document.getElementById('Posterbox')
				uni.showLoading({
					title: '生成中...'
				});
				html2canvas(dom, {
					width: dom.outerWidth, //dom 原始宽度
					height: dom.outerHeight,
					scrollY: 0,
					scrollX: 0,
					// scale:2,
					scale: 1.5,
					// dpi: 1450,
					dpi:window.devicePixelRatio *4,
					useCORS: true
				  }).then((canvas) => {
					uni.hideLoading()
					//成功后调用返回canvas.toDataURL返回图片的imageData
					let imageData = canvas.toDataURL('image/png', 1)
					const arrayBuffer = uni.base64ToArrayBuffer(imageData);
					// #ifdef APP-PLUS
						const bitmap = new plus.nativeObj.Bitmap("img");
						bitmap.loadBase64Data(imageData, function() {
							const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
							bitmap.save(url, {
								overwrite: true, // 是否覆盖
								// quality: 100  // 取值范围为1-100，1表示使用最低的图片质量（保存后的图片文件最小）、100表示使用最高的图片质量（保存后的图片文件最大）； 默认值为50
							}, (i) => {
								uni.saveImageToPhotosAlbum({
									filePath: url,
									success: function() {
										uni.showToast({
											title: '图片保存成功',
											icon: 'none'
										})
										bitmap.clear()
									}
								});
							}, (e) => {
								uni.showToast({
									title: '图片保存失败',
									icon: 'none'
								})
								bitmap.clear()
							});
						}, (e) => {
							uni.showToast({
								title: '图片保存失败',
								icon: 'none'
							})
							bitmap.clear()
						});
					// #endif
					
					// #ifdef H5 || MP-WEIXIN
						const fileName= 'image.png'
						// 将ArrayBuffer转换为Blob对象
						var arr = imageData.split(","),
							mime = arr[0].match(/:(.*?);/)[1],
							bstr = atob(arr[1]),
							n = bstr.length,
							u8arr = new Uint8Array(n);
						  while (n--) {
							u8arr[n] = bstr.charCodeAt(n);
						  }
						  // 将Blob对象转换成文件并下载到本地
						  var blob = new Blob([u8arr], {
							type: mime
						  });
						  console.log(imageData , 'imageData');
							// 安卓环境
						  if (uni.getSystemInfoSync().platform === 'android') {
							  
							   uni.hideLoading()
							   this.$refs.popupPoster.close()
							   uni.uploadFile({
							   	url: '/dev-api/uploadPic',  //仅为示例，非真实的接口地址
							   	filePath: imageData,
							   	name: 'file',
							   	header:{
							   		"Authorization":'Bearer  ' + nowToken
							   	},
							   	formData: {
							   		img: 'file',
							   	},
							   	success: (uploadFileRes) => {
									console.log(uploadFileRes , 'dsfsf----');
									let imgarr=[]
									let res = JSON.parse(uploadFileRes.data);
									let url = this.serverHost + res.fileName;
									imgarr[0]=url
									uni.previewImage({ //图片预览
										current: 0,
										urls: imgarr
									});
							   	},
								fail: (err) => {
									alert(JSON.stringify(err))
								}
							   });
						  }else{
							  var a = document.createElement('a');
							  a.download = fileName;
							  a.href = URL.createObjectURL(blob);
							  a.click();	
						  }
					//#endif
				})
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	.search-box{
		background-color: #F2F2F3;
		border-radius: 36rpx;
		height: 72rpx;
		width: 320rpx;
		padding: 0 0 0 12rpx;
		.search-input-box{
			input{
				width: 280rpx;
			}
		}
		.image100 , .img-box{
			width: 50rpx;
			height: 50rpx;
		}
		.screen-box{
			width: 300rpx;
			.screen-item{
				.text{
					color: #1456FE;
				}
				image{
					width: 40rpx;
					height: 40rpx;
				}
				.shai{
					width: 60rpx;
					height: 60rpx;
				}
			}
		}
		.tab-box{
			width: 100%;
			height: 100rpx;
			background-color: #fff;
		}
		.search-btn{
			width: 128rpx;
			height: 60rpx;
			color: #fff;
			text-align: center;
			line-height: 60rpx;
			background: $uni-color-primary;
			border-radius: 50rpx;
		}
	}
	.content{
		padding: 20rpx;
		padding-bottom: 100rpx;
		.card-box{
			padding: 20rpx;
			width: 100%;
			
			background: #FFFFFF;
			border-radius: 16rpx;
			.code-box{
				color: #fff;
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				text-align: center;
				line-height: 100rpx;
				background-color: $uni-color-primary;
			}
			
			.tag{
				padding: 10rpx 20rpx;
				border-radius: 30rpx;
				font-size: 24rpx;
				.icon{
					width: 30rpx;
					height: 30rpx;
					margin-right: 6rpx;
				}
			}
			.tag1{
				background: #DBE5FF;
				color: #1456FE;
			}
			.tag2{
				background: #FFEAE4;
				color: #FF600F;
			}
			.grey{
				color: #5D5D5D;
			}
			.data-box{
				padding: 20rpx;
				width: 100%;
				
				background: #F1F3F7;
				border-radius: 16rpx;
				.tab_itemorder {
					width: 25%;
					text-align: center;
				}
			}
			.tab-item{
				color: #F79E06;
			}
		}
	}
	.Posterpopup {
		width: 680rpx;
		padding: 10rpx;
		border-radius: 12rpx;
		// background-color: #007aff;
		// background-image: url("../../static/23.png");
		
	
		&-image {
			// width: 600rpx;
			width: 100%;
			height: 900rpx;
			margin: auto;
		}
	
		&-code {
			display: flex;
			justify-content: center;
			margin: 30rpx 0;
		}
	}
	// 批量分佣弹窗
	.Piliangfypopup {
		width: 680rpx;
		padding: 10rpx;
		border-radius: 12rpx;
		background-color: #fff;
	
		.title {
			text-align: center;
			font-weight: 600;
			font-size: 32rpx;
			margin: 16rpx 0;
		}
	
		&-input {
			width: 80%;
			margin: 26rpx auto;
			padding: 8rpx;
			border: 1px solid #999;
			border-radius: 8rpx;
	
			input {
				padding-left: 8rpx;
				width: 100%;
			}
		}
	}
	::v-deep .uni-navbar__header-btns-right{
		display: none;
	}
	::v-deep .uni-navbar__header-btns-left{
		display: none;
	}
	::v-deep .uni-navbar__header-container{
		align-items: center;
	}
</style>